<?php
namespace app\admin\controller;

use app\common\model\AuthRule as AuthRuleModel;
use app\common\model\Admin as AdminModel;
use app\common\model\Config as CfgModel;
use think\captcha\Captcha;
use think\Db;
use think\facade\Cache;
use think\facade\Env;
use think\facade\Url;
use think\facade\Session;

class Index extends BaseAdmin
{
	protected $noNeedLogin = ['login','captcha'];
    protected $noNeedRight = ['logout'];

    //初始化
    public function initialize()
    {
		parent::initialize();
		$this->assign('menu_tag','menu_one'); //菜单组标记，与系统菜单节点相对应
    }

    public function index()
    {
      $_list = [];
      $exp_num = 0;
      if(count($_list) > 0)
      {
        foreach ($_list as $key => $value) {
          if($value['except_time'] <= time()) $exp_num++;
        }
      }
      $arr = [
         'admin_total' => AdminModel::count(),
         'seller_total' => 0,
         'group_total' => 0,
         'exp_total' => $exp_num,
      ];
      
      //print_r(CfgModel::getJiuZhenConfig()); //微信支付配置

      $this->assign('info',$arr);
      return $this->view->fetch();
    }

    /*
       修改修改资料
    */
    public function profile()
    {
        if($this->request->isAjax())
        {
            $v_id = intval($this->request->post('v_id'));
            $v_nick_name = trim($this->request->post('v_nick_name'));
            $v_pwd = trim($this->request->post('v_pwd'));
            $v_safecode = trim($this->request->post('v_safecode'));
            $v_phone = trim($this->request->post('v_phone'));
            $v_sex = intval($this->request->post('v_sex'));
            $v_img = trim($this->request->post('v_img'));
            $iData = [
                'nickname' => $v_nick_name, //真实姓名
                'img' => $v_img, //头像
                'sex' => $v_sex, //性别，1男2女0未知
                's_phone' => $v_phone, //手机号码
            ];
            if($v_pwd)
            {
              $iData['admin_pwd'] = __re_md5($v_pwd);
            }
            AdminModel::where(['id' => $v_id])->update($iData);
            return json(['err' => '0', 'msg' => '您的账号信息修改成功']);
        }else{
           return $this->view->fetch();
        }
    }
    /*
     菜单节点搜索
    */
    public function search()
    {
		if($this->request->isAjax())
		{
          $word = trim($this->request->post('word'));
          $page = intval($this->request->post('page'));
		      //分页
          $limit = intval($this->pageNum) > 0 ? intval($this->pageNum) : 20;
          $offset = intval(($page - 1) * intval($limit));  //开始位置
          //条件
          $_map = [];
          if($word)
          {
             $_map[] = ['title|url|remark', 'LIKE', '%' . $word . '%'];
          }
          $arrList = AuthRuleModel::where($_map)->order('sort desc')->limit($offset, $limit)->select();
          $arrCount = AuthRuleModel::where($_map)->count();
          if($arrCount <= 0 || count($arrList) <= 0)
          {
             return json(['err' => '1', 'msg' => 'Sorry！暂未搜索出您想要的数据。']);
          }
          foreach($arrList as $k => &$v)
          {
              $arrList[$k]['icon'] = !$v['icon'] ? '/' : trim($v['icon']);
              $arrList[$k]['status'] = intval($v['status']) > 0 ? '启用' : '禁用';
              $v['url'] = Url::build($v['url']);
          }
          return json(['err' => '0', 'page' => $page , 'limit' => $limit, 'total' => $arrCount,'list' => $arrList]);
        }else{
            $_word = trim($this->request->get('top_search')); 
            if(!$_word)
            {
              $this->redirect(Url::build('admin/index/index'), '', 302);
            }
            $page = intval($this->request->get('p')); //url 页码参数  ?p=1
            $this->assign('page', $page > 0 ? $page : '1');
            $this->assign('word',$_word);
            return $this->view->fetch();
        }
    }

    /**
     * 全局图片上传 调用方法  接收上传的图片
     */
    public function uploadpic()
    {
      if(!$this->request->isPost())
      {
        $this->redirect(Url::build('admin/index/index'), '', 302);
      }
      $savedir = trim($this->request->post('savedir'));
      $inputname = trim($this->request->post('inputname'));
      $inputname = !$inputname ? 'file' : $inputname;
      if($savedir)
      {
        $aliOssPath = "upload/" . strtolower($savedir);
        $path = Env::get('root_path') . "public/upload/" . strtolower($savedir);
        $pathUrl = "/upload/" . strtolower($savedir). "/";
        $imgUrl = $this->site['weburl'] . "/" . "upload/" . strtolower($savedir) . "/";
      }else{
        $aliOssPath = "upload";
      	$path = Env::get('root_path') . "public/upload";
      	$pathUrl = "/upload/";
      	$imgUrl = $this->site['weburl'] . "/" . "upload/";
      }
      if(!is_dir($path))
      {
        mkdir($path, 0777);
        chmod($path, 0777);
      }
      $files = $this->request->file($inputname);
      $infos = $files->validate(['ext' => 'jpg,png,gif,jpeg,bmp'])->move($path);
      if($infos)
      {
          $save_name = str_replace("\\",'/',$infos->getSaveName());
          $res = [
              'err' => '0',
              'img_path' => $pathUrl . $save_name, //返回文件保存的路径
              'img_url' => $imgUrl . $save_name, //返回文件web url
              'oss_url' => '', //阿里云OSS url
          ];
          //上传至阿里云OSS
          if(intval($this->ossConfig['up_alioss_onoff']) > 0)
          {
            $oss = Alioss::instance($this->ossConfig);
            $ossRes = $oss->uploadAliOssSimple($aliOssPath.'/'.$save_name,$path.'/'.$save_name);
            //上传出错写下日志
            if(isset($ossRes['err']) && (int)$ossRes['err'] <= 0)
            {
              $res['oss_url'] = trim($ossRes['oss_url']);
            }else{
              _writeSystemLog($ossRes);
            }
          }
          return json($res);
      } else {
          return json(['err' => '1','msg' => $files->getError()]);
      }
    }
    /**
     * 全局excel文件上传
    */
    public function upload_excel()
    {
      if(!$this->request->isPost())
      {
        $this->redirect(Url::build('admin/index/index'), '', 302);
      }
      $savedir = trim($this->request->post('savedir'));
      $inputname = trim($this->request->post('inputname'));
      $inputname = !$inputname ? 'file' : $inputname;
      if($savedir)
      {
        $path = Env::get('root_path') . "public/upload/" . strtolower($savedir);
        $pathUrl = "/upload/" . strtolower($savedir). "/";
        $imgUrl = $this->site['weburl'] . "/" . "upload/" . strtolower($savedir) . "/";
      }else{
        $path = Env::get('root_path') . "public/upload";
        $pathUrl = "/upload/";
        $imgUrl = $this->site['weburl'] . "/" . "upload/";
      }
      if(!is_dir($path))
      {
        mkdir($path, 0777);
        chmod($path, 0777);
      }
      $files = $this->request->file($inputname);
      $infos = $files->validate(['ext' => 'xls,xlsx'])->move($path);
      if($infos)
      {
          $save_name = str_replace("\\",'/',$infos->getSaveName());
          $res = [
              'err' => '0',
              'path' => $pathUrl . $save_name, //返回文件保存的路径
              'url' => $imgUrl . $save_name, //返回文件web url
          ];
          return json($res);
      } else {
          return json(['err' => '1','msg' => $files->getError()]);
      }
    }
    /**
     * 删除一个图片
     * /upload/caigouhetong/20200929/2c928daee85039a7ffcf9673f1bf77ea.jpg
     */
    public function uploadpic_del()
    {
      if(!$this->request->isAjax())
      {
        $this->redirect(Url::build('admin/index/index'), '', 302);
      }
      $path = trim($this->request->post('path'));
      if(!$path)
      {
        return json(['err' => '1', 'msg' => '图片路径参数错误']);
      }
      if(substr($path,0,1) != '/') $path = '/'.$path;
      $path = Env::get('root_path') . "public" . $path;
      $r = @unlink($path);
      if(!$r) return json(['err' => '2', 'msg' => '图片删除失败']);
      return json(['err' => '0', 'msg' => '图片删除成功']);
    }
    /**
     * 清空系统缓存
     */
    public function wipecache()
    {
		$res = __clearnSystemCache();
        if ($res) {
            return json(['err' => '0', 'msg' => '已成功清除系统缓存！']);
        } else {
            return json(['err' => '0', 'msg' => '清除缓存失败!']);
        }
    }
    /*
    登录
    */
    public function login($backurl = '',$redirect = '')
    {
        if ($this->request->isPost() && $this->request->isAjax()) {
			
            $username = trim($this->request->post('name')); //账号
            $password = trim($this->request->post('pwd')); //密码
			$captcha = trim($this->request->post('yzm')); //验证码
            $captcha_key = trim($this->request->post('captcha_key')); //验证码对应的key名称
			if(!captcha_check($captcha,$captcha_key)){
				return json(['err' => '1', 'msg' => '对不起，图片验证码输入错误']);
			}
            $res = $this->auth->login($username, $password);
            return json($res);
        } else {
            if (!$this->admin) {
                $this->assign([
                    'captcha_key' => md5($this->site['client_uuid'] . '_22'),
                    'backurl' => !$backurl ? Url::build('admin/index/index') : urldecode(trim($backurl)),
                ]);
                return $this->view->fetch();
            } else {
                $this->success("您已登录，禁止重复登录！", $this->request->get('url', Url::build('admin/index/index')));
            }
        }
    }
    /*
       退出登录
    */
    public function logout()
    {
        $this->auth->logout();
        $this->success('您已成功退出系统', 'admin/index/login');
    }
	
	//登录 图片验证码
    public function captcha($soure = '', $key = 'admin')
    {
		$config =    [
			// 验证码字体大小
			'fontSize'    =>    80,    
			// 验证码位数
			'length'      =>    4,   
			// 关闭验证码杂点
			'useNoise'    =>    true,
			//设置验证码字符为纯数字
			'codeSet'     =>    'T01G2B34R56H789T',
		];
		$captcha = new Captcha($config);
		return $captcha->entry($key);
	}
}
